package com.ksd.modules.rbac.roles.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ksd.commons.BaseServiceImpl;
import com.ksd.modules.rbac.roles.entity.SysRoles;
import com.ksd.modules.rbac.roles.entity.SysUserRoles;
import com.ksd.modules.rbac.roles.mapper.SysUserRolesMapper;
import com.ksd.modules.rbac.roles.service.ISysUserRolesService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户角色表 服务实现类
 * </p>
 *
 * @author Auto Generator
 * @since 2023-08-13
 */
@Service
public class SysUserRolesService extends BaseServiceImpl<SysUserRolesMapper, SysUserRoles> implements ISysUserRolesService {


    @Override
    public List<Long> findUserRoles(Long userId) {
        List<SysRoles> roles = this.baseMapper.findRoles(userId);
        List<Long> roleIds = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(roles)) {
            roleIds = roles.stream().map(c -> c.getId()).collect(Collectors.toList());
        }
        return roleIds;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveUserRoles(Long userId, String roleIds) {
        if (StringUtils.isEmpty(roleIds)) {
            return false;
        }
        // 1: 根据用户删除已经授权的角色
        LambdaQueryWrapper<SysUserRoles> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUserRoles::getUserId, userId);
        this.remove(lambdaQueryWrapper);

        // 2: 开始授权
        String[] roleIdsArr = roleIds.split(",");
        List<SysUserRoles> sysUserRolesList = new ArrayList<>();
        for (String roleId : roleIdsArr) {
            SysUserRoles sysUserRoles = new SysUserRoles();
            sysUserRoles.setUserId(userId);
            sysUserRoles.setRoleId(Long.valueOf(roleId));
            sysUserRolesList.add(sysUserRoles);
        }
        this.saveBatch(sysUserRolesList);
        return true;
    }


}

